import axios, {type AxiosInstance} from 'axios';
import router from '@/router'
import {ElMessage} from 'element-plus'
import {useAuthStore} from "@/stores/auth";

const axiosInstance: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})

axiosInstance.interceptors.request.use((config) => {
    const authStore = useAuthStore();
    config.headers['Authorization'] = authStore.getToken()
    return config
}, (error) => {
    console.log(error)
    Promise.reject(error)
})

axiosInstance.interceptors.response.use((response) => {
    const authStore = useAuthStore();
    if (typeof response.data !== 'object') {
        ElMessage.error('服务端异常！')
        return Promise.reject(response)
    }
    if (response.data.code != "00000") {
        if (response.data.message) {
            ElMessage.error(response.data.message)
        }
        // 登录已过期
        if (response.data.code == 'A0230') {
            // 移除 token
            authStore.removeToken();
            authStore.removeNickName();
            authStore.removeUid();
            router.push({path: '/login'})
        }

        return Promise.reject(response.data)
    }

    return response.data
}, (error) => {
    ElMessage.error('网络异常！')
    console.log(error)
    return Promise.reject(error)
})

export default axiosInstance